<?php
namespace app\Common\command;

use app\massage\model\Bonus;
use app\massage\model\GroupRatio;
use app\massage\model\Identity;
use app\massage\model\IdentityList;
use app\massage\model\User;
use app\massage\model\UserGroup;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 服务订单分润
 */
class IdentityBonus extends Command
{
    protected $identity_list_model;
    protected $identity_model;
    protected $user_model;
    protected $bonus_model;
    protected $group_model;
    protected $group_ratio_model;

    public function __construct() {

        parent::__construct();

        $this->identity_list_model = new IdentityList();
        $this->identity_model = new Identity();
        $this->user_model = new User();
        $this->bonus_model = new Bonus();
        $this->group_model = new UserGroup();
        $this->group_ratio_model = new GroupRatio();
    }
    protected function configure()
    {
        $this->setName('identity_bonus')->setDescription('招商订单分润');
    }

    //执行
    protected function execute(Input $input, Output $output)
    {
        $where = [
            'pay_status' => 1,
            'handle_status' => 0,
        ];
        $order_lists = $this->identity_list_model->where($where)->select();
        if(!count($order_lists)){
            $output->writeln('招商订单分润完成。已处理：0');
        }
        Db::startTrans();
        try {
            foreach ($order_lists as $order) {
                //1.按身份计算佣金
                $this->handleIdentity($order);
                //2.按用户组计算佣金
                $this->handleGroup($order);
            }
            //3.修改招商订单状态为：已处理
            $order_ids = array_column($order_lists->toArray(),'id');
            $where = [
                ['id','in',$order_ids],
                ['handle_status','=',0]
            ];
            $this->identity_list_model->where($where)->update(['handle_status' => 1]);
        }catch(\Exception $e){
            Db::rollback();
            $output->writeln('招商订单分润执行出错：'.$e->getMessage());
        }
        Db::commit();
        $output->writeln('招商订单分润完成。已处理：'.count($order_lists));
    }

    //按身份计算佣金
    protected function handleIdentity($order)
    {
        $user = $this->user_model->where(['id' => $order['user_id']])->find();
        if(!$user['pid']){
            return true;
        }
        $total_amount = $order['amount'];
        $parent = $this->user_model->where(['id' => $user['pid']])->find();
        if(!$parent['identity_id']){
            return true;
        }
        $order_identity = $this->identity_model->dataInfo(['id' => $order['identity_id']]);
        $parent_identity = $this->identity_model->dataInfo(['id' => $parent['identity_id']]);
        $rule = json_decode($parent_identity['rule'],true);
        switch ($order_identity['type']){
            case 1://云店技师
                $type_id = 1;
                $commission_type = 2;
                break;
            case 2://代言人
                $type_id = 2;
                $commission_type = 1;
                break;
            case 3://门店渠道商
                $type_id = 3;
                $commission_type = 3;
                break;
            default:
                $type_id = 1;
                $commission_type = 2;
                break;
        }
        $ratio = 0;
        foreach ($rule as $item) {
            if($item['type_id'] == $type_id){
                $ratio = $item['ratio'];
                break;
            }
        }
        $bonus = round($total_amount * ($ratio/100),2);
        $bonus_data = [
            'user_id' => $parent['id'],
            'relation_id' => $order['id'],
            'type' => $commission_type,
            'bonus' => $bonus,
            'send_status' => 0,
            'create_time' => time(),
        ];
        $this->bonus_model->insert($bonus_data);
    }

    //按用户组计算佣金
    protected function handleGroup($order)
    {
        $order_identity = $this->identity_model->dataInfo(['id' => $order['identity_id']]);
        $group_list = $this->group_model->dataList(['status' => 1]);
        $total_amount = $order['amount'];
        switch ($order_identity['type']){
            case 1://云店技师
                $type = 1;
                $commission_type = 2;
                $field = 'cloud_store_ratio';
                break;
            case 2://代言人
                $type = 1;
                $commission_type = 1;
                $field = 'cloud_store_ratio';
                break;
            case 3://门店渠道商
                $type = 2;
                $commission_type = 3;
                $field = 'channel_ratio';
                break;
            default:
                $type = 1;
                $commission_type = 2;
                $field = 'cloud_store_ratio';
                break;
        }
        foreach ($group_list as $group) {
            $group_ratio = $group[$field];
            $group_amount = round($total_amount * ($group_ratio/100),2);
            if($group_amount <= 0){
                break;
            }
            $dis = [
                'group_id' => $group['id'],
                'type' => $type,
            ];
            $user_ratios = $this->group_ratio_model->dataList($dis);
            foreach ($user_ratios as $user_ratio) {
                $bonus = round($group_amount * ($user_ratio['ratio']/100),2);
                $bonus_data = [
                    'user_id' => $user_ratio['user_id'],
                    'relation_id' => $order['id'],
                    'type' => $commission_type,
                    'bonus' => $bonus,
                    'send_status' => 0,
                    'create_time' => time(),
                ];
                $res = $this->bonus_model->insert($bonus_data);
                if(!$res){
                    Db::rollback();
                    break;
                }
            }
        }
    }
}